package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class OtherStudentDao implements BaseStudentDao {
    private static ArrayList<Student> stuList = new ArrayList<>();

    static {
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("itheima-edu-info-manager\\stu.txt"));
            //将文件读取到一个大的字节数组当中
             byte[] bys = new byte[1024];
             int len = bis.read(bys);
            //将读取到的字节数组作为构造参数,创建字符串
            String stuStr = new String(bys,0,len);

            String[] stuStrArray = stuStr.split(System.lineSeparator());
            for (String s : stuStrArray) {
                String[] split = s.split(",");
                Student stu = new Student(split[0],split[1],split[2],split[3]);
                stuList.add(stu);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        /*Student stu1 = new Student("heima001", "阿拉松", "20", "1999-10-11");
        Student stu2 = new Student("heima002", "彭小晏", "21", "1998-10-12");

        stuList.add(stu1);
        stuList.add(stu2);*/
    }

    //创建Student学生数组,长度为5

    //添加学生
    public boolean addStudent(Student stu) {
        stuList.add(stu);
        return true;
    }

    //查询
    public Student[] findAllStudent() {

        Student[] students = new Student[stuList.size()];

        for (int i = 0; i < students.length; i++) {
            students[i] = stuList.get(i);
        }

        return students;
    }

    //删除学生
    public void deleteStudent(String delId) {
        int index = getIndex(delId);

        //将该索引位置的元素用null替换
        stuList.set(index, null);
    }

    //获取指定学号的索引位置
    public int getIndex(String delId) {
        //查找学生id在数组中的索引位置
        int index = -1;
        for (int i = 0; i < stuList.size(); i++) {
            Student student = stuList.get(i);
            if (student != null && student.getId().equals(delId)) {
                index = i;
                break;
            }
        }
        return index;
    }

    //修改学生
    public void updateStudent(String updateId, Student stu) {
        //获取指定学号的索引位置
        int index = getIndex(updateId);
        //将stu覆盖指定索引位置
        stuList.set(index, stu);
    }
}
